import os
import SocketServer, time 
 
class MyServer(SocketServer.BaseRequestHandler):  
  userInfo = {  
    'yangsq'  : 'yangsq',  
    'hudeyong' : 'hudeyong',  
    'mudan'   : 'mudan' }  
 
  def handle(self):  
    print 'Connected from', self.client_address  
      
    while True:  
      receivedData = self.request.recv(1024)  
      
      if not receivedData: 
        #time.sleep(1)
        continue 
      request = receivedData.strip('0')  
      print 'request:'+request
      kvs = request.split('#')
      
      dictKV = dict()
      length = kvs[0]  
      print 'size:'+length
      for kv in kvs :
        keyValue = kv.split('=')
        if len(keyValue)==2 :
          dictKV[keyValue[0]] = keyValue[1]
        else :
          dictKV['len']=keyValue
      
      if dictKV['ApiName'] == 'DownStepFile' :  
      	print 'stepfile req:'+dictKV['serverFile']  
        #guidStep = receivedData.split(':')[-1]  
        path =  './stepfile/'+dictKV['serverFile'] 
        print 'send F:'+path  
        if os.access(path, os.R_OK):
          sfile = open(path, 'rb')  
          while True:  
            data = sfile.read(1024)  
            if not data:  
              break 
            while len(data) > 0:  
              intSent = self.request.send(data)  
              data = data[intSent:]  
 
          print 'send Finish'
          self.request.sendall('EOF')  
        else:  
          print 'send Fail:'+path  
          self.request.sendall('invalid')  
            
      elif receivedData == 'bye':  
        break         
      print 'receivedData:'+receivedData  
 
    self.request.close()  
      
    print 'Disconnected from', self.client_address  
    print 
 
if __name__ == '__main__':  
  print 'Server is started\nwaiting for connection...\n'  
  srv = SocketServer.ThreadingTCPServer(('0.0.0.0', 50000), MyServer)  
  srv.serve_forever()       

def startServer():
  print 'File Server is started\nwaiting for connection...\n'  
  srv = SocketServer.ThreadingTCPServer(('0.0.0.0', 50000), MyServer)  
  srv.serve_forever()     	
